<template>
	<view class="content">
		<!-- #ifdef MP -->
		<view class="flex align-center fixed-top bg-white" style="height: 44px">
			<!-- 搜索框 -->
			<view class="ml-2 flex align-center flex-1 rounded-circle px-1"
				style="height: 40px; background-color: #f6f7f8; color: #959fa0" @click="GoSearch()">
				<image :src="Domain_ICON + '/search.png'" mode="" style="margin-right: 8px; width: 25px; height: 25px">
				</image>
				<text class="font">点击搜索</text>
			</view>
			<image @click="orderify()" style="width: 65rpx" :src="Domain_ICON + '/orders.png'" mode="widthFix"></image>
		</view>
		<view style="height: 44px"></view>
		<!-- #endif -->
		<!-- 搜索到的商品卡片 -->
		<view class="flex align-center justify-center flex-column" v-if="goods.length > 0 ? false : true">
			<image style="width: 300rpx" :src="Domain_ICON + '/zanwugouwu.png'" mode="widthFix"></image>
			<text>暂无相关内容...</text>
		</view>
		<!--  -->

		<view v-else class="px-3 pt-3">
			<scroll-view scroll-y="true" class="scroll-Y flex flex-wrap justify-between" :enable-flex="true">
				<view class="mb-3 rounded-lg bg-light" style="width: 320rpx; height: 500rpx; position: relative"
					v-for="(item, index) in goods" :key="index" @click="
            handleDetails(
              item.Article_SerialNumber,
              item.Sales_Unit_Price_SerialNumber,
              item.Store_SerialNumber,
              item.specifications[0].Sales_Unit_Price
            )
          ">
					<image class="rounded-lg" style="width: 320rpx; height: 320rpx" :src="Domain_IMG + item.Picture_URL"
						:lazy-load="true" mode="">
					</image>
					<view class="ml-2 text-ellipsis" style="70rpx">
						<text style="display: block" class="w-100 font text-ellipsis">{{
              item.Article_Name
            }}</text>
						<text style="display: block" class="font-small text-secondary">{{
              item.specifications[0].Specifications_Name
            }}</text>
						<text style="display: block"
							class="font-small text-secondary">仅剩{{ item.specifications[0].Stock_Remain }}件</text>
						<text style="display: block"
							class="h4 font-weight-bold">￥{{ item.specifications[0].Sales_Unit_Price }}</text>
					</view>
					<view v-if="
              !Car.some(
                (i) => i.Article_SerialNumber == item.Article_SerialNumber
              )
            " class="add rounded-circle text-center bg-info text-light font-weight-bold font-lg" @click.stop="
              addShopCar(
                item.Store_SerialNumber,
                item.specifications[0].Sales_Unit_Price,
                item.specifications[0].Sales_Unit_Price_Stock_SerialNumber,
                item.Article_SerialNumber,
                item.specifications[0].Article_Specifications_SerialNumber,
                item.specifications[0].Unit_Price,
				item.specifications[0].Sign
              )
            ">
						+</view>
					<view v-else class="flex justify-center align-center rounded-circle"
						style="position: absolute; right: 20rpx; bottom: 20rpx">
						<view @click.stop="subGoods(item.Article_SerialNumber)"
							class="font-md text-center text-white flex justify-center align-center"
							:style="{ backgroundColor: '#17a2b8' }" style="width: 50rpx; height: 50rpx">-</view>
						<view class="text-center font bg-white border" style="width: 50rpx; height: 50rpx"
							:style="'border-top:1rpx solid #17a2b8;border-bottom:1rpx solid #17a2b8; color:#17a2b8; box-sizing: border-box;'">
							{{
                parseInt(
                  Car.filter(
                    (i) => i.Article_SerialNumber == item.Article_SerialNumber
                  )[0].Quantity
                )
              }}
						</view>
						<view @click.stop="addGoods(item.Article_SerialNumber)"
							class="font-md text-center text-white flex justify-center align-center"
							:style="{ backgroundColor: '#17a2b8' }" style="width: 50rpx; height: 50rpx">+</view>
					</view>
				</view>
				<view class="text-center py-2 w-100">
					<text class="text-muted font-small">{{ BottomText }}</text>
				</view>
			</scroll-view>
		</view>
		<!--  -->
		<!-- 右侧悬浮按钮 -->
		<view class="button flex flex-column-reverse">
			<view class="shadow mt-2 bg-white rounded-circle flex justify-center align-center"
				style="width: 100rpx; height: 100rpx; position: relative" @click="handleBtn(item.title)"
				v-if="item.isShow" v-for="(item, index) in btn" :key="index">
				<i v-if="item.title == 'car' && total1 > 0" class="bg-danger rounded-circle text-white px-1 font-sm"
					style="position: absolute; top: -5rpx; left: -5rpx">{{ total1 }}</i>
				<image :src="Domain_ICON + item.icon" style="width: 50rpx; height: 50rpx" mode=""></image>
				<button id="shareBtn" class="rounded-circle" open-type="share" v-if="item.title == 'share'">
					分享
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import Toolkit from "@/mixins/Toolkit.js";
	import {
		WX2GoodsIdAction,
		WXGoodsIdBlurred
	} from "@/api/group.js";
	import {
		WXEditShopCarQuantity
	} from "@/api/article.js";
	import {
		WXShopCarQuantity
	} from "@/api/WeChat.js";
	export default {
		data() {
			return {
				goods: [], //通过id查询商品列表,
				Domain_IMG: app.globalData.Domain_IMG, //全局变量域名
				UserSearchforRecords: [], //用户的搜索记录
				i1: 0, //超过9个记录之后替换位置的索引
				form: {
					ShopColumn_Id: "",
					page: 1,
					limit: 10,
				},
				Car: [],
				form1: {
					Article_Name: "",
					page: 1,
					limit: 4,
					App_ID: app.globalData.appid,
					Open_ID: app.globalData.openid,
					Enterprise_Info_SerialNumber: app.globalData.enterprise,
				},
				btn: [{
						//右侧悬浮按钮
						title: "top",
						icon: "/top.png",
						isShow: false,
					},
					{
						title: "serve",
						icon: "/serve.png",
						isShow: true,
					},
					{
						title: "car",
						icon: "/shop_car.png",
						isShow: true,
					},
				],
				total: 1,
				total1: 0,
				BottomText: "下拉获取更多商品",
				timer: null,
				ReachBottom: false,
				scrollY: 0,
				Domain_ICON: app.globalData.Domain_ICON, //全局变量域名
			};
		},
		onPageScroll(e) {
			this.scrollY = e.scrollTop;
		},
		watch: {
			scrollY: function(newValue, oldValue) {
				if (newValue > 500) {
					this.btn[0].isShow = true;
				} else {
					this.btn[0].isShow = false;
				}
			},
		},
		onReachBottom() {
			console.log("触底了");
			if (this.BottomText != "暂无更多商品") {
				//只要没拿到所有商品就继续发送请求
				if (this.form1.Article_Name == "") {
					this.form.page++;
					this.thorw();
				} else {
					this.form1.page++;
					this.thorw1();
				}
			}
		},
		onLoad(options) {
			if (options.key == undefined) {
				uni.showLoading({
					title: "加载中...",
				});
				this.form.ShopColumn_Id = options.id;
				this.getGoodsById(this.form);
			} else {
				//本地存储搜索记录保存到本地数组
				if (uni.getStorageSync("UserSearchforRecords")) {
					this.UserSearchforRecords = uni.getStorageSync("UserSearchforRecords");
				}
				//本地数组每次都在首位添加一次输入框的值
				this.UserSearchforRecords.unshift(options.key);
				//如果数组超过9位
				if (this.UserSearchforRecords.length > 9) {
					//每次替换掉数组末位的旧数据
					this.UserSearchforRecords.pop(options.key);
				}
				//数组去重,防止搜索记录重复
				this.UserSearchforRecords = Toolkit.unique1(this.UserSearchforRecords);
				//未来还要收集用户搜索记录,分析用户喜好~
				uni.showLoading({
					title: "查询中...",
				});
				this.form1.Article_Name = options.key;
				this.getGoodsByName(this.form1);
			}
		},
		onShow() {
			// this.ShopCarQuantity(app.globalData.openid)
			this.ShopGoods();
		},
		methods: {
			handleDetails(
				Article_SerialNumber,
				Sales_Unit_Price_SerialNumber,
				Store_SerialNumber,
				Sales_Unit_Price
			) {
				//点击进入"商品详情"页
				uni.navigateTo({
					url: "/pages/index/details?Article_SerialNumber=" +
						Article_SerialNumber +
						"&Sales_Unit_Price_SerialNumber=" +
						Sales_Unit_Price_SerialNumber +
						"&Store_SerialNumber=" +
						Store_SerialNumber +
						"&Sales_Unit_Price=" +
						Sales_Unit_Price,
				});
			},
			handleBtn(title) {
				//点击屏幕左侧悬浮按钮或底部"首页"、"客服"按钮后对应操作
				if (title == "top") {
					//回到页面顶部
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 300,
					});
				} else if (title == "serve") {
					//进入"客服"页
					uni.navigateTo({
						url: "../serves/serves",
					});
				} else if (title == "car") {
					//进入"购物车"页
					uni.redirectTo({
						url: "../shopcar/shopcar",
					});
				} else if (title == "index") {
					//进入"首页"
					uni.redirectTo({
						url: "/pages/index/index",
					});
				}
			},
			async subGoods(Article_SerialNumber) {
				if (this.loading) return;
				uni.showLoading({
					title: "提交中...",
				});
				this.loading = true;
				const res = await WXEditShopCarQuantity({
					Article_SerialNumber,
					Open_ID: app.globalData.openid,
					Type: 0,
				});
				this.loading = false;
				if (res.Status == "success") {
					const res1 = await WXShopCarQuantity({
						App_ID: app.globalData.appid,
						Open_ID: app.globalData.openid,
						Enterprise_Info_SerialNumber: app.globalData.enterprise,
					});
					if (res1.Status == "success") {
						this.total1 = 0;
						res1.Data.forEach((item) => {
							this.total1 = this.total1 + parseInt(item.Quantity);
						});
						this.Car = res1.Data;
						uni.hideLoading();
					}
				}
			},
			async addGoods(Article_SerialNumber) {
				if (this.loading) return;
				uni.showLoading({
					title: "提交中...",
				});
				this.loading = true;
				const res = await WXEditShopCarQuantity({
					Article_SerialNumber,
					Open_ID: app.globalData.openid,
					Type: 1,
				});
				this.loading = false;
				if (res.Status == "success") {
					const res1 = await WXShopCarQuantity({
						App_ID: app.globalData.appid,
						Open_ID: app.globalData.openid,
						Enterprise_Info_SerialNumber: app.globalData.enterprise,
					});
					if (res1.Status == "success") {
						this.total1 = 0;
						res1.Data.forEach((item) => {
							this.total1 = this.total1 + parseInt(item.Quantity);
						});
						this.Car = res1.Data;
						uni.hideLoading();
					}
				}
			},
			async ShopGoods() {
				const res = await WXShopCarQuantity({
					App_ID: app.globalData.appid,
					Open_ID: app.globalData.openid,
					Enterprise_Info_SerialNumber: app.globalData.enterprise,
				});
				if (res.Status == "success") {
					this.total1 = 0;
					res.Data.forEach((item) => {
						this.total1 = this.total1 + parseInt(item.Quantity);
					});
					this.Car = res.Data;
				}
			},
			GoSearch() {
				//跳转到"搜索"页
				uni.navigateTo({
					url: "/pages/index/search",
				});
			},
			orderify() {
				//跳转到"订单"页
				uni.navigateTo({
					url: "/pages/my/order?id=0",
				});
			},
			async getGoodsById(data) {
				//获取对应id的商品(分页)
				uni.showLoading({
					title: "加载中...",
				});
				this.BottomText = "加载中...";
				const res = await WX2GoodsIdAction(data);
				uni.hideLoading();
				this.goods.push(...res.tableData);
				this.total = Number(res.limit);
				if (this.total == this.goods.length) {
					this.BottomText = "暂无更多商品";
				} else {
					this.BottomText = "下拉获取更多商品";
				}
			},
			thorw1(secend = 200) {
				//防抖函数
				this.timer = null;
				clearInterval(this.timer);
				this.timer = setTimeout(() => {
					this.getGoodsByName(this.form1);
				}, secend);
			},
			thorw(secend = 200) {
				//防抖函数
				this.timer = null;
				clearInterval(this.timer);
				this.timer = setTimeout(() => {
					this.getGoodsById(this.form);
				}, secend);
			},
			async getGoodsByName(data) {
				uni.showLoading({
					title: "加载中...",
				});
				this.BottomText = "加载中...";
				const res = await WXGoodsIdBlurred(data);
				uni.hideLoading();
				console.log(res);
				this.goods.push(...res.tableData);
				this.total = Number(res.limit);
				uni.setStorageSync("UserSearchforRecords", this.UserSearchforRecords);
				console.log(this.total, this.goods.length);
				if (this.total == this.goods.length) {
					this.BottomText = "暂无更多商品";
				} else {
					this.BottomText = "下拉获取更多商品";
				}
			},
			time() {
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1;
				let days = new Date().getDate();
				let hour = new Date().getHours();
				let minutes = new Date().getMinutes();
				let second = new Date().getSeconds();
				if (month < 10) {
					month = "0" + month;
				}
				if (days < 10) {
					days = "0" + days;
				}
				if (hour < 10) {
					hour = "0" + hour;
				}
				if (minutes < 10) {
					minutes = "0" + minutes;
				}
				if (second < 10) {
					second = "0" + second;
				}
				this.times =
					year +
					"-" +
					month +
					"-" +
					days +
					" " +
					hour +
					":" +
					minutes +
					":" +
					second;
			},
			addShopCar(
				Store_SerialNumber,
				Sales_Unit_Price,
				Sales_Unit_Price_Stock_SerialNumber,
				Article_SerialNumber,
				Article_Specifications_SerialNumber,
				Unit_Price,
				Sign
			) {
				//加入购物车
				this.time();
				if (!this.loading) {
					this.loading = true;
					uni.showLoading({
						title: "提交中...",
					});
					uni.request({
						header: {
							"Content-Type": "application/x-www-form-urlencoded",
						},
						url: app.globalData.Domain_Name + "/WXCheckShopCarAction", //
						method: "POST",
						data: {
							Open_ID: app.globalData.openid,
							App_ID: app.globalData.appid,
							Sales_Unit_Price_Stock_SerialNumber,
						},
						success: (res) => {
							if (res.data.length == 0) {
								uni.request({
									header: {
										"Content-Type": "application/x-www-form-urlencoded",
									},
									url: app.globalData.Domain_Name + "/getAddAction?grant_type=wechat_program", //
									method: "POST",
									data: {
										Data: JSON.stringify({
											sales_order: [{
												Sales_Order_SerialNumber: "",
												Store_SerialNumber: Store_SerialNumber,
												Sales_Date: this.times,
												Open_ID: app.globalData.openid,
												Sales_Amount: Sales_Unit_Price,
												Collection_Amount: 0,
												Sales_ID: "xiaoshou1",
												Receive_Type: 0,
												Refund_Type: 0,
												Row_Status: 8,
												App_ID: app.globalData.appid,
												Enterprise_Info_SerialNumber: app
													.globalData.enterprise,
												Children: {
													sales_order_detail: [{
														Sales_Order_Detail_SerialNumber: "",
														Sales_Order_SerialNumber: "",
														Sales_Unit_Price_Stock_SerialNumber: Sales_Unit_Price_Stock_SerialNumber,
														Article_SerialNumber: Article_SerialNumber,
														Article_Specifications_SerialNumber: Article_Specifications_SerialNumber,
														Sign: Sign,
														Quantity: 1,
														Unit_Price: Unit_Price,
														Sales_Unit_Price: Sales_Unit_Price,
														Amount: Sales_Unit_Price,
														Receive_Type: 0,
														Refund_Type: 0,
														Row_Status: 8,
														Enterprise_Info_SerialNumber: app
															.globalData
															.enterprise,
													}, ],
												},
											}, ],
										}),
										Open_ID: app.globalData.openid,
									},
									success: (res) => {
										if (res.data.Status == "success") {
											uni.showToast({
												title: "已加入购物车！",
												icon: "none",
											});
											this.total1++;
											this.ShopGoods();
										} else {
											uni.showToast({
												title: "系统繁忙！",
												icon: "error",
											});
										}
									},
									complete: () => {
										this.loading = false;
										uni.hideLoading();
									},
								});
							} else {
								this.loading = false;
								uni.hideLoading();
								uni.showToast({
									title: "购物车存在该商品！",
									icon: "none",
								});
							}
						},
					});
				}
			},
		},
	};
</script>

<style>
	.add {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
	}

	.button {
		position: fixed;
		bottom: 200rpx;
		right: 20rpx;
		width: 100rpx;
	}
</style>